# coding=utf8

import os
import sys
import re

from openpyxl.reader.excel import load_workbook

reload(sys)
sys.setdefaultencoding('utf-8')

PREFIXES = [',', '\'']
SUFFIXES = [':']


def split_symbol(symbol,syllable):
    matched = re.search(r'(\s*)(\[?)([^\[\]]+)(\]?)(\s*)', symbol, re.M | re.I)
    # print line
    # if str(matched) == 'None':
    #     print line
    #     print "end"

    symbols = matched.group(3)
    new_syllable = list(syllable)


    # buf = []
    # parts = []
    # i = -1
    # k = -1
    up_index = -1
    down_index = -1
    up = '\''
    down = ','
    up_symbol = re.search(up,symbol,re.M | re.I)
    down_symbol = re.search(down,symbol,re.M | re.I)
    if str(up_symbol)!='None':
        up_index = symbols.index("\'")

    if str(down_symbol)!='None':
        down_index = symbols.index(",")
    # print up_index
    # print down_index

    if up_index >=0:
        if up_index==0:
            new_syllable[0] = up + new_syllable[0]
        else :
            syllable_index = find_all_index(syllable, ".")
            for j in syllable_index:
                if up_index <= j:
                    new_syllable[j] =  "." + up
                    break
    # print new_syllable
    if down_index>=0:
        if down_index == 0:
            new_syllable[0] = down + new_syllable[0]
        else :
            syllable_index = find_all_index(syllable, ".")
            for j in syllable_index:
                if down_index <= j:
                    new_syllable[j] = "." + down
                    break
    # print new_syllable

    # print  ''.join(new_syllable)
    syllable = ''.join(new_syllable)
    syllable_list = syllable.split('.')

    up_pattern = re.compile(r'\'')
    down_pattern = re.compile(r',')
    l = 0
    while l < len(syllable_list):
        up_match = up_pattern.match(syllable_list[l])
        down_match = down_pattern.match(syllable_list[l])
        if up_match :
            syllable_list[l] = syllable_list[l].replace("\'","*")
            syllable_list[l] += "*"

        if down_match :
            syllable_list[l] = syllable_list[l].replace(",", "~")
            syllable_list[l] += "~"

        l = l + 1

    # print '.'.join(syllable_list)
    return '.'.join(syllable_list)

    # syllable_index = find_all_index(syllable, ".")
    # for j in syllable_index:
    #     if up_index <= j:
    #         new_syllable[j].replace(".", "." + up)
    #         break
    #     elif down_index <= j:
    #         new_syllable[j].replace(".", "." + down)
    #         break



    # while i < len(symbols):
    #     current = symbols[i]
    #     syllable_index = find_all_index(syllable,".")
    #     # current_zend = syllable[i]
    #     n3xt = ''
    #     if (current == "\'" or current == ",") and i == 0:
    #         new_syllable = current+syllable
    #     # elif (current == "\'" | current == ",") & current_zend == '\.' & i != 0 :
    #     #     current_zend.replace(".","."+current)
    #     else :
    #         for j in syllable_index :
    #             if i<=j:
    #                 new_syllable[j].replace(".","."+current)
    #                 break
    #     i = i + 1
    # print new_syllable
    # return new_syllable


def get_time_quick(line):
    line = line.replace(',', '')
    line = line.replace('\'', '')
    line = line.replace(':', '')
    return len(line)

def find_all_index(arr,item):
    return [i for i,a in enumerate(arr) if a==item]

def process(work_book, course):
    word_sheet_name = "%s_word" % course
    print word_sheet_name
    wb = load_workbook(filename=work_book)
    syllable_sheet_name = "%s_syllable" % course
    in_ws = wb.get_sheet_by_name(word_sheet_name)
    sheet_names = wb.get_sheet_names()
    if syllable_sheet_name in sheet_names:
        out_ws = wb.get_sheet_by_name(syllable_sheet_name)
    else:
        out_ws = wb.create_sheet(syllable_sheet_name)
    out_row = 2
    print in_ws.max_row
    for r in range(2, in_ws.max_row + 1):
        word_id = in_ws.cell(row=r, column=1).value
        word = in_ws.cell(row=r, column=2).value
        symbol = in_ws.cell(row=r, column=3).value
        syllable = in_ws.cell(row=r, column=5).value
        print syllable
        parts = split_symbol(symbol,syllable)
        out_ws.cell(row=out_row, column=1).value = word_id
        out_ws.cell(row=out_row, column=2).value = word
        out_ws.cell(row=out_row, column=3).value = symbol
        out_ws.cell(row=out_row, column=4).value = syllable
        out_ws.cell(row=out_row, column=5).value = parts
        # print parts
        # for i in range(len(parts) - 1, -1, -1):
            # out_ws.cell(row=out_row, column=1).value = word_id
            # line = ''.join(parts[i:])
            # if i == 0:
            #     out_ws.cell(row=out_row, column=2).value = '[' + line + ']'
            # else:
            #     out_ws.cell(row=out_row, column=2).value = line
            # out_ws.cell(row=out_row, column=3).value = 2 * get_time_quick(line)
            # out_ws.cell(row=out_row, column=4).value = 4 * get_time_quick(line)
            # parts = split_symbol(symbol, syllable)
            # out_ws.cell(row=out_row, column=1).value = word_id
            # out_ws.cell(row=out_row, column=2).value = word
            # out_ws.cell(row=out_row, column=3).value = syllable
            # out_ws.cell(row=out_row, column=4).value = parts
        out_row = out_row + 1
    wb.save(work_book)

